<template>
  <div>
    <div class="table-page-search-wrapper" style="margin-top: 20px">
      <a-row type="flex" justify="space-between" align="middle">
        <a-col :span="9">
          <div style="margin-left: 0px; float: left; display: flex; align-item: center">
            <div style="margin-top: 5px">邮件服务器：</div>
            <a-select
              v-model:value="listQuerySingle.es_id"
              placeholder="请选择"
              style="width: 180px"
            >
              <a-select-option key="" value=""> 全部服务器 </a-select-option>
              <a-select-option v-for="d in allServer" :key="d._id" :value="d._id">
                {{ d.title }}
              </a-select-option>
            </a-select>
          </div>
        </a-col>
        <a-col :span="14">
          <div style="margin-right: 0px; float: right; display: flex; align-item: center">
            <a-radio-group
              v-model:value="listQuerySingle.date_num"
              style="margin-right: 8px"
              @change="changeDateNumSingle"
            >
              <a-radio-button :value="0">今日</a-radio-button>
              <a-radio-button :value="7">近7天</a-radio-button>
              <a-radio-button :value="15">近15天</a-radio-button>
              <a-radio-button :value="30">近30天</a-radio-button>
            </a-radio-group>
            <a-range-picker v-model:value="listQuerySingle.date_range" @change="changeDateSingle" />
          </div>
        </a-col>
        <a-col :span="1">
          <div style="margin-right: 0px; float: right; display: flex; align-item: center">
            <a-tooltip placement="top">
              <template #title>
                <span>刷新数据</span>
              </template>
              <a-button @click="reloadList">
                <template #icon>
                  <SyncOutlined />
                </template>
              </a-button>
            </a-tooltip>
          </div>
        </a-col>
      </a-row>
      <div style="background: #ececec; padding: 20px; margin-top: 25px">
        <a-row :gutter="16">
          <a-col :span="4">
            <a-card>
              <a-statistic title="发送总量" :value="totalData.sv" style="margin-right: 50px" />
            </a-card>
          </a-col>
          <a-col :span="4">
            <a-card>
              <a-statistic
                title="发送失败总量"
                :value="totalData.sfv"
                style="margin-right: 50px"
                :value-style="{ color: '#cf1322' }"
              />
            </a-card>
          </a-col>
          <a-col :span="4">
            <a-card>
              <a-statistic
                title="发送成功总量"
                :value="totalData.ssv"
                style="margin-right: 50px"
                :value-style="{ color: '#3f8600' }"
              />
            </a-card>
          </a-col>
          <a-col :span="4">
            <a-card>
              <a-statistic
                title="发送成功率"
                :value="totalData.ssv_sv_rate"
                style="margin-right: 50px"
              >
                <template #suffix> % </template>
              </a-statistic>
            </a-card>
          </a-col>
          <a-col :span="4">
            <a-card>
              <a-statistic title="邮件阅读总量" :value="totalData.rv" style="margin-right: 50px" />
            </a-card>
          </a-col>
          <a-col :span="4">
            <a-card>
              <a-statistic title="邮件阅读率" :precision="2" :value="totalData.rv_sv_rate">
                <template #suffix> % </template>
              </a-statistic>
            </a-card>
          </a-col>
        </a-row>
      </div>
      <div id="single_line" style="margin-top: 25px"></div>
    </div>
    <a-divider />
    <div style="margin-top: 20px; font-weight: bold; font-size: 16px; margin-bottom: 20px">
      邮箱分析(限时体验)
    </div>
    <a-table
      :columns="columns"
      :rowKey="(record) => record._id"
      :dataSource="dataList.data"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #url_title="{ text: record }">
        <span style="cursor: pointer; color: #1890ff" @click="viewUrl(record)">{{ record }}</span>
      </template>
    </a-table>
    <a-modal
      v-model:open="visible"
      :title="listQuerySingle.email + ' 邮箱分析'"
      style="top: 20px"
      :width="1200"
      :footer="null"
    >
      <a-tabs v-model:activeKey="listQuerySingle.email_tab" type="card">
        <a-tab-pane key="1" tab="邮件服务器" />
        <a-tab-pane key="2" tab="邮件标题" />
        <a-tab-pane key="3" tab="打开情况" />
      </a-tabs>
      <div id="pie_line" style="margin-top: -10px"></div>
      <a-table
        :columns="columns2"
        :rowKey="(record) => record._id"
        :dataSource="dataHostList.data"
        :loading="loadingHost"
        :pagination="false"
        @change="handleHostTableChange"
      >
        <template #url_title="{ text: record }">
          <span v-if="record == ''" style="cursor: pointer; color: #1890ff">无标题</span>
          <span v-else style="cursor: pointer; color: #1890ff">{{ record }}</span>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, onMounted, ref, watch } from 'vue'
import {
  Row,
  Col,
  Divider,
  Drawer,
  Card,
  Tooltip,
  Statistic,
  RadioGroup,
  RangePicker,
  Modal,
  Tag
} from 'ant-design-vue'
import {
  SyncOutlined,
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
  DownOutlined,
  QrcodeOutlined,
  CopyOutlined
} from '@ant-design/icons-vue'
import { allLogData, getFromAds, getAllServerList, getFromSingleEmail } from '@/api/email'
import { useRouter } from 'vue-router'
import { todayDate, getRangeDate } from '@/utils/common'
import dayjs, { Dayjs } from 'dayjs'
import { Line, Pie } from '@antv/g2plot'

export default defineComponent({
  name: 'Captcha',
  components: {
    SyncOutlined,
    PlusOutlined,
    EditOutlined,
    ExclamationCircleOutlined,
    DownOutlined,
    CopyOutlined,
    QrcodeOutlined,
    DeleteOutlined,
    [Modal.name]: Modal,
    [Tag.name]: Tag,
    [Row.name]: Row,
    [Card.name]: Card,
    [Tooltip.name]: Tooltip,
    [RadioGroup.name]: RadioGroup,
    [RangePicker.name]: RangePicker,
    [Divider.name]: Divider,
    [Statistic.name]: Statistic,
    [Drawer.name]: Drawer,
    [Col.name]: Col
  },
  setup() {
    const formRef = ref()
    const router = useRouter()
    const dateFormat = 'YYYY-MM-DD'
    const state = reactive<any>({
      loading: true,
      loadingHost: true,
      drawerShow: false,
      visible: false,
      oauthVisible: false,
      today: todayDate(),
      dataList: [],
      allServer: [],
      dataHostList: [],
      allUrlData: [],
      secretShow: {},
      totalData: {},
      title: router.currentRoute.value.query?.title,
      singleLineRender: '',
      dataTime: '',
      pieHostRender: '',
      hostPie: ref(),
      singleLine: ref(),
      activeKey: ref('1'),
      listQuery: {
        pageNo: 1,
        es_id: '',
        email: '',
        pageSize: 15,
        date_range: [],
        date_range_format: [],
        date_num: -1
      },
      listQueryHost: {
        pageNo: 1,
        _id: '',
        pageSize: 15,
        host: '',
        date_range: [],
        date_range_format: [],
        date_num: -1
      },
      listQuerySingle: {
        es_id: '',
        email_tag: '1',
        date_range: [],
        date_range_format: [],
        date_num: 0
      },
      pagination: {
        pageSizeOptions: ['15'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSize: 15
      },
      paginationHost: {
        pageSizeOptions: ['15', '30', '50'],
        showSizeChanger: true,
        total: 1,
        showTotal: (total) => `共 ${total} 条数据`,
        pageSize: 15
      },
      columns: [
        {
          title: '邮箱地址',
          dataIndex: '_id',
          slots: { customRender: 'url_title' }
        },
        {
          title: '发送量',
          dataIndex: 'count'
        },
        {
          title: '发送量占比',
          dataIndex: 'rate'
        }
      ],
      columns2: [
        {
          title: '类别',
          dataIndex: '_id',
          slots: { customRender: 'url_title' }
        },
        {
          title: '发送量',
          dataIndex: 'count'
        },
        {
          title: '发送量占比',
          dataIndex: 'rate'
        }
      ]
    })
    onMounted(() => {
      getRangeDay()
      getServerDataList()
      getRangeDaySingle('auto')
    })
    function getServerDataList() {
      getAllServerList({}).then((res) => {
        state.allServer = res
      })
    }
    function reloadList() {
      getRangeDayDataSingle()
      getFromData()
    }

    watch(
      () => state.listQuerySingle.es_id,
      () => {
        getRangeDayDataSingle()
        getFromData()
      }
    )
    watch(
      () => state.listQuerySingle.email_tab,
      () => {
        switch (state.listQuerySingle.email_tab) {
          case '1':
            state.columns2[0].title = '邮件服务器'
            break
          case '2':
            state.columns2[0].title = '邮件标题'
            break
          case '3':
            state.columns2[0].title = '类别'
            break
          default:
            state.columns2[0].title = '类别'
            break
        }
        getEmailAnaData()
      }
    )
    function changeDateNum(e) {
      state.listQuery.date_num = e.target.value
      getRangeDay()
    }
    function changeDateNumSingle(e) {
      state.listQuerySingle.date_num = e.target.value
      getRangeDaySingle('click')
    }
    function changeDateSingle(e) {
      state.listQuerySingle.date_range = e
      getRangeDayDataSingle()
      getFromData()
    }
    function viewUrl(e) {
      state.visible = true
      state.listQuerySingle.email = e
      getEmailAnaData()
    }
    function getRangeDaySingle(operate) {
      let end = ''
      let start = ''
      end = getRangeDate(0)
      start = end
      if (state.listQuerySingle.date_num != 0) {
        start = getRangeDate((state.listQuerySingle.date_num - 1) * -1)
      }
      state.listQuerySingle.date_range = ref<[Dayjs, Dayjs]>([
        dayjs(start, dateFormat),
        dayjs(end, dateFormat)
      ])
      if (operate == 'auto') {
        setTimeout(() => {
          console.log(operate)
          getRangeDayDataSingle()
          getFromData()
        }, 1000)
      } else {
        getRangeDayDataSingle()
        getFromData()
      }
    }
    function getRangeDay() {
      let end = ''
      let start = ''
      end = getRangeDate(-1)
      start = end
      if (state.listQuery.date_num != -1) {
        start = getRangeDate(state.listQuery.date_num * -1)
      }
      state.listQuery.date_range = ref<[Dayjs, Dayjs]>([
        dayjs(start, dateFormat),
        dayjs(end, dateFormat)
      ])
    }

    function getRangeDayDataSingle() {
      state.listQuerySingle.date_range_format[0] =
        state.listQuerySingle.date_range[0].format(dateFormat)
      state.listQuerySingle.date_range_format[1] =
        state.listQuerySingle.date_range[1].format(dateFormat)
      allLogData(state.listQuerySingle).then((res) => {
        let data = res.data.chart
        state.totalData = res.data.total
        if (state.singleLineRender == 'update') {
          state.singleLine.update({
            data
          })
        } else {
          state.singleLine = new Line('single_line', {
            data,
            xField: 'date',
            smooth: true,
            yField: 'value',
            seriesField: 'category',
            yAxis: {
              label: {
                // 数值格式化为千分位
                formatter: (v) => `${v}`.replace(/\d{1,3}(?=(\d{3})+$)/g, (s) => `${s},`)
              }
            }
          })
          state.singleLine.render()
          state.singleLineRender = 'update'
        }
      })
    }
    function handleTableChange(e) {
      state.loading = true
      state.pagination.pageSize = e.pageSize
      state.listQuery.pageSize = e.pageSize
      state.listQuery.pageNo = e.current
      state.pagination.current = e.current
      getFromData()
    }
    function handleHostTableChange(e) {
      state.loadingHost = true
      state.listQueryHost.pageSize = e.pageSize
      state.listQueryHost.pageNo = e.current
      getEmailAnaData()
    }
    function getEmailAnaData() {
      state.listQuerySingle.date_range_format[0] =
        state.listQuerySingle.date_range[0].format(dateFormat)
      state.listQuerySingle.date_range_format[1] =
        state.listQuerySingle.date_range[1].format(dateFormat)
      getFromSingleEmail(state.listQuerySingle).then((res) => {
        state.loadingHost = false
        state.dataHostList = res
        state.paginationHost.total = res.totalCount
        let data = res.data
        if (state.pieHostRender == 'update') {
          state.hostPie.update({
            data
          })
        } else {
          state.hostPie = new Pie('pie_line', {
            appendPadding: 10,
            data,
            angleField: 'count',
            colorField: '_id',
            radius: 0.75,
            label: {
              type: 'spider',
              labelHeight: 28,
              content: '{name}\n{percentage}'
            },
            interactions: [{ type: 'element-selected' }, { type: 'element-active' }]
          })
          state.hostPie.render()
          state.pieHostRender = 'update'
        }
      })
    }
    function getFromData() {
      state.listQuery.date_range_format[0] = state.listQuerySingle.date_range[0].format(dateFormat)
      state.listQuery.date_range_format[1] = state.listQuerySingle.date_range[1].format(dateFormat)
      getFromAds(state.listQuery).then((res) => {
        state.loading = false
        state.dataList = res
        state.pagination.total = res.totalCount
      })
    }
    const FormState = reactive<any>({
      _id: '',
      title: '',
      url: '',
      expire: ''
    })
    const FormRule = {
      title: [{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }],
      expire: [{ required: true, message: '请选择有效期', trigger: ['blur', 'change'] }],
      url: [{ required: true, message: '请输入源链地址', trigger: ['blur', 'change'] }]
    }
    function short_url_tj(res) {
      state.listQuerySingle._id = res._id
      getRangeDay()
      getRangeDaySingle('auto')
    }
    return {
      ...toRefs(state),
      changeDateSingle,
      formRef,
      changeDateNum,
      viewUrl,
      changeDateNumSingle,
      FormState,
      handleTableChange,
      reloadList,
      handleHostTableChange,
      short_url_tj,
      FormRule,
      router
    }
  }
})
</script>

<style scoped></style>
